package cn.shanguoyu.netty.test.day01;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * @description:
 * @author：sgy
 * @date: 2023-06-20
 */
public class NettyClient {
    public static void main(String[] args) throws Exception {
        // 线程池(组)
        EventLoopGroup group = new NioEventLoopGroup();
        // 客户端启动助手
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap
                    .group(group) // Netty客户端会使用这个线程组来工作
                    .channel(NioSocketChannel.class) // 指定使用NIO的通讯模式
                    .remoteAddress(new InetSocketAddress("127.0.0.1", 8080)) // 指定通讯端口
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                        }
                    });
            // 异步连接到服务器，sync()会阻塞到连接完成
            ChannelFuture future = bootstrap.connect().sync();
            // 阻塞当前线程，直到客户端的Channel被关闭
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }

    }
}
